<template>
  <div class="course-detail-page">
    <el-card class="detail-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h2>{{ course.name || '课程名称' }}</h2>
          <el-tag type="success" v-if="course.price === 0">免费</el-tag>
          <el-tag type="danger" v-else>¥{{ course.price }}</el-tag>
        </div>
      </template>

      <!-- Main content area -->
      <el-tabs v-model="activeTab" class="course-tabs">
        <el-tab-pane label="课程介绍" name="intro">
          <div class="intro-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <img :src="course.img || 'https://via.placeholder.com/400x300'" class="course-image" />
              </el-col>
              <el-col :span="12" class="course-info">
                <h3>课程描述</h3>
                <p>{{ course.desc || course.description || '暂无课程描述' }}</p>

                <div class="info-item">
                  <strong>教师:</strong>
                  <span>{{ course.teacher && course.teacher.length > 0 ? course.teacher.join(', ') : '暂无教师信息' }}</span>
                </div>

                <div class="info-item">
                  <strong>分类:</strong>
                  <span>{{ course.category && course.category.length > 0 ? course.category.join(', ') : '暂无分类信息' }}</span>
                </div>

                <!-- 课程操作按钮区域 -->
                <div class="course-actions">
                  <!-- 免费课程或已购买课程 -->
                  <template v-if="course.price === 0 || isPurchased">
                    <el-button 
                      type="primary" 
                      size="large"
                      @click="startLearning" 
                      class="enroll-button"
                      :loading="loading"
                    >
                      <el-icon><VideoPlay /></el-icon>
                      {{ isPurchased ? '继续学习' : '立即学习' }}
                    </el-button>
                    <div v-if="isPurchased" class="purchase-status">
                      <el-tag type="success" size="small">
                        <el-icon><Check /></el-icon>
                        已购买
                      </el-tag>
                    </div>
                  </template>
                  
                  <!-- 付费课程且未购买 -->
                  <template v-else>
                    <div class="purchase-info">
                      <div class="price-display">
                        <span class="price-label">课程价格：</span>
                        <span class="price-value">¥{{ course.price }}</span>
                      </div>
                      <el-button 
                        type="danger" 
                        size="large"
                        @click="purchaseCourseAction" 
                        class="purchase-button"
                        :loading="isPurchasing"
                      >
                        <el-icon><ShoppingCart /></el-icon>
                        {{ isPurchasing ? '购买中...' : '立即购买' }}
                      </el-button>
                    </div>
                  </template>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <el-tab-pane label="课程资料" name="materials">
          <div class="materials-content">
            <h3>课程章节</h3>
            <el-empty v-if="chapters.length === 0" description="暂无章节"></el-empty>
            <el-tree :data="chapters" :props="chapterProps" node-key="chapterID" default-expand-all @node-click="handleChapterClick"></el-tree>
          </div>
        </el-tab-pane>

        <el-tab-pane label="课程评论" name="comments">
          <div class="comments-content">
            <div class="comment-input-area">
              <el-input
                v-model="newCommentContent"
                :placeholder="replyingToUserName ? `回复 ${replyingToUserName}:` : '发表评论...'"
                type="textarea"
                :rows="3"
                clearable
              ></el-input>
              <div class="comment-submit-actions">
                <el-button v-if="replyingToCommentId" type="text" @click="replyingToCommentId = null; replyingToUserName = ''; newCommentContent = '';">取消回复</el-button>
                <el-button type="primary" @click="submitComment">提交评论</el-button>
              </div>
            </div>

            <el-divider v-if="comments.length > 0">评论列表</el-divider>

            <div v-if="comments.length > 0" class="comment-list-container">
              <CommentItem
                v-for="comment in comments"
                :key="comment.commentID"
                :comment="comment"
                @reply="handleReply"
              />
            </div>
            <el-empty v-else description="暂无评论"></el-empty>
          </div>
        </el-tab-pane>
      </el-tabs>

    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getCourseChapters, getChapterComments, getCourseList, purchaseCourse, checkCoursePurchaseStatus } from '../api/course'
import { postComment } from '../api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '../stores/user'
import { VideoPlay, Check, ShoppingCart } from '@element-plus/icons-vue'
import CommentItem from '../components/CommentItem.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const courseId = ref(null)
const course = ref({}) // 存储课程详情
const chapters = ref([]) // 存储课程章节
const loading = ref(false)
const activeTab = ref('intro') // 默认激活 '课程介绍' tab

const comments = ref([]) // 存储评论列表
const newCommentContent = ref('') // 新评论内容
const replyingToCommentId = ref(null) // 回复的评论ID
const replyingToUserName = ref('') // 回复的用户名

const currentChapterIdForComments = ref(null); // 用于加载评论的章节ID

// 课程购买相关状态
const isPurchased = ref(false) // 是否已购买
const isCheckingPurchase = ref(false) // 是否正在检查购买状态
const isPurchasing = ref(false) // 是否正在购买中

const chapterProps = {
  label: 'name',
  children: 'children'
}

// 检查课程购买状态
const checkPurchaseStatus = async () => {
  if (!userStore.isLoggedIn || !courseId.value) return
  
  isCheckingPurchase.value = true
  try {
    const res = await checkCoursePurchaseStatus(courseId.value)
    if (res.code === 1) {
      isPurchased.value = res.data.isPurchased || false
    }
  } catch (error) {
    console.error('Failed to check purchase status:', error)
    // 如果检查失败，默认为未购买
    isPurchased.value = false
  } finally {
    isCheckingPurchase.value = false
  }
}

// 购买课程
const purchaseCourseAction = async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再购买课程')
    router.push('/login')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定购买课程"${course.value.name}"吗？购买后将可以学习所有章节内容。`,
      '购买确认',
      {
        confirmButtonText: '确定购买',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }
    )
    
    isPurchasing.value = true
    const res = await purchaseCourse(courseId.value)
    
    if (res.code === 1) {
      ElMessage.success('课程购买成功！现在可以开始学习了')
      isPurchased.value = true
    } else {
      ElMessage.error(res.message || '购买失败，请重试')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '购买失败，请稍后再试')
      console.error('Purchase error:', error)
    }
  } finally {
    isPurchasing.value = false
  }
}

// 开始学习课程
const startLearning = () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再学习课程')
    router.push('/login')
    return
  }

  if (!isPurchased.value && course.value.price > 0) {
    ElMessage.warning('请先购买课程后再学习')
    return
  }

  // 如果有章节，跳转到第一个章节
  if (chapters.value.length > 0) {
    const firstChapter = findFirstLeafChapter(chapters.value)
    if (firstChapter) {
      router.push({
        name: 'materialViewer',
        params: {
          courseId: courseId.value,
          chapterId: firstChapter.chapterID
        }
      })
    } else {
      ElMessage.info('课程暂无学习内容')
    }
  } else {
    ElMessage.info('课程暂无章节内容')
  }
}

// 查找第一个叶子章节
const findFirstLeafChapter = (chapList) => {
  for (const chap of chapList) {
    if (chap.children && chap.children.length > 0) {
      const found = findFirstLeafChapter(chap.children)
      if (found) return found
    } else {
      return chap // 找到第一个没有子章节的作为叶子章节
    }
  }
  return null
}

const fetchCourseBaseInfo = async (id) => {
  // 获取所有课程，找到当前课程的基础信息
  try {
    const res = await getCourseList({ page: 1, pageSize: 9999 })
    if (res.code === 1 && Array.isArray(res.data.items)) {
      return res.data.items.find(item => item.courseID == id) || {}
    }
  } catch (e) {
    console.error('获取课程基础信息失败', e)
  }
  return {}
}

const fetchCourseChapters = async () => {
  loading.value = true
  try {
    // 先获取基础信息
    const baseInfo = await fetchCourseBaseInfo(courseId.value)
    // 再获取章节等详细信息
    const res = await getCourseChapters(courseId.value)
    if (res.code === 1) {
      // 合并基础信息和详细信息
      course.value = {
        ...res.data,
        img: baseInfo.img,
        category: baseInfo.category,
        teacher: baseInfo.teacher
      }
      chapters.value = res.data.chapters || []
      
      // 获取课程信息后检查购买状态
      await checkPurchaseStatus()
    } else {
      ElMessage.error(res.message || '获取课程章节失败')
      course.value = {}
      chapters.value = []
    }
  } catch (error) {
    console.error('Failed to fetch course chapters:', error)
    ElMessage.error(error.message || '获取课程章节失败，请重试')
    course.value = {}
    chapters.value = []
  } finally {
    loading.value = false
  }
}

const handleChapterClick = async (data, node) => {
  // 如果是父章节，不处理点击事件，或者仅展开/收起
  if (data.children && data.children.length > 0) {
    return;
  }

  const chapterID = data.chapterID
  if (!chapterID) {
    ElMessage.warning('当前章节没有有效的ID。')
    return
  }

  // 检查是否已购买课程
  if (!isPurchased.value && course.value.price > 0) {
    ElMessage.warning('请先购买课程后再学习章节内容')
    return
  }

  // 跳转到 MaterialViewer 页面
  router.push({
    name: 'materialViewer',
    params: {
      courseId: courseId.value,
      chapterId: chapterID
    }
  })
}

// 提交评论
const submitComment = async () => {
  if (!newCommentContent.value.trim()) {
    ElMessage.warning('评论内容不能为空！')
    return
  }

  let chapterIDToComment = currentChapterIdForComments.value; // 优先使用已确定的章节ID

  if (!chapterIDToComment && chapters.value.length > 0) {
    // 尝试找到第一个叶子章节作为默认评论章节
    const firstLeafChapter = findFirstLeafChapter(chapters.value);
    if (firstLeafChapter) {
      chapterIDToComment = firstLeafChapter.chapterID;
    }
  }

  if (!chapterIDToComment) {
    ElMessage.error('无法确定评论所属的章节，请先选择一个章节或确保课程有章节。');
    return;
  }

  try {
    const res = await postComment({
      content: newCommentContent.value,
      chapterID: chapterIDToComment,
      parentCommentID: replyingToCommentId.value
    })
    if (res.code === 1) {
      ElMessage.success('评论发表成功！')
      newCommentContent.value = ''
      replyingToCommentId.value = null
      replyingToUserName.value = ''
      fetchComments(chapterIDToComment) // 刷新评论列表
    } else {
      ElMessage.error(res.message || '评论发表失败！')
    }
  } catch (error) {
    console.error('Failed to post comment:', error)
    ElMessage.error(error.message || '评论发表失败，请重试！')
  }
}

// 处理回复点击事件
const handleReply = (commentId, userName) => {
  replyingToCommentId.value = commentId
  replyingToUserName.value = userName
  newCommentContent.value = `@${userName} `
}

// 格式化评论列表为树形结构
const formatCommentsAsTree = (commentList) => {
  const commentMap = {};
  commentList.forEach(comment => {
    commentMap[comment.commentID] = { ...comment, children: [] };
  });

  const rootComments = [];
  commentList.forEach(comment => {
    if (comment.parentCommentID === null || !commentMap[comment.parentCommentID]) {
      // 顶级评论或父评论不存在，视为顶级评论
      rootComments.push(commentMap[comment.commentID]);
    } else {
      // 子评论，添加到父评论的children中
      commentMap[comment.parentCommentID].children.push(commentMap[comment.commentID]);
    }
  });

  return rootComments;
};

// 获取评论列表
const fetchComments = async (chapterIdToFetch) => {
  if (!chapterIdToFetch) return;

  loading.value = true;
  try {
    const res = await getChapterComments(chapterIdToFetch);
    if (res.code === 1) {
      comments.value = formatCommentsAsTree(res.data || []);
    } else {
      ElMessage.error(res.message || '获取评论失败');
      comments.value = [];
    }
  } catch (error) {
    console.error('Failed to fetch comments:', error);
    ElMessage.error(error.message || '获取评论失败，请重试');
    comments.value = [];
  } finally {
    loading.value = false;
  }
};

// 监听 activeTab 的变化，当切换到 comments Tab 时加载评论
watch(activeTab, (newTab) => {
  if (newTab === 'comments') {
    // 确保在加载评论前，courseId和chapters数据已经可用
    if (courseId.value && chapters.value.length > 0) {
      // 确保有一个可用于评论的章节ID
      let chapterIDForComments = null;
      // 这里的逻辑需要和MaterialViewer.vue中获取material的逻辑保持一致，
      // 即找到当前激活的资料所属的章节，或默认的第一个有资料的章节。
      // 为简化，我们暂时用课程的第一个叶子章节作为评论的章节。
      const firstLeafChapter = findFirstLeafChapter(chapters.value);

      if (firstLeafChapter) {
        currentChapterIdForComments.value = firstLeafChapter.chapterID;
        fetchComments(currentChapterIdForComments.value);
      } else {
        ElMessage.info('当前课程暂无章节可供评论。');
        comments.value = [];
      }
    } else {
      // 如果课程信息还没加载完成，等待onMounted中的fetchCourseChapters完成
      // 或者可以添加一个延迟/重试机制
      console.warn('Course details or chapters not yet loaded for comments.');
    }
  }
});

onMounted(() => {
  courseId.value = route.params.id
  if (courseId.value) {
    fetchCourseChapters()
  }
})
</script>

<style scoped>
.course-detail-page {
  width: 70vw; /* User's previous modification */
  padding: 20px;
}

.detail-card {
  max-width: 100%;
  margin: 20px auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 28px;
  color: #303133;
}

.course-tabs {
  margin-top: 20px;
}

.intro-content, .materials-content, .comments-content {
  padding: 20px 0;
}

.course-image {
  width: 100%;
  height: auto;
  border-radius: 4px;
}

/* Removed global course-video as it's now in materials tab */
/* .course-video {
  width: 100%;
  height: 300px;
  background-color: #000;
  border-radius: 4px;
} */

/* .chapter-video {
  width: 100%;
  height: auto; /* Adjust height dynamically for chapter videos */
/*  max-height: 250px;
  background-color: #000;
  border-radius: 4px;
  margin-bottom: 10px;
} */

.course-info {
  padding-left: 20px;
}

.course-info h3 {
  font-size: 22px;
  color: #303133;
  margin-bottom: 15px;
}

.course-info p {
  font-size: 16px;
  line-height: 1.8;
  color: #606266;
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.info-item strong {
  margin-right: 10px;
  color: #303133;
}

.enroll-button {
  margin-top: 20px;
  width: 150px;
}

.el-divider {
  margin: 40px 0;
}

/* Removed material-item styles as they are no longer here */
/* .material-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  background-color: #FAFAFA;
}

.material-item p {
  margin-bottom: 5px;
}

.material-item a {
  color: #409EFF;
  text-decoration: none;
} */

.course-actions {
  margin-top: 20px;
}

.purchase-info {
  margin-top: 10px;
}

.price-display {
  margin-bottom: 10px;
}

.price-label {
  margin-right: 10px;
}

.price-value {
  font-size: 16px;
  color: #303133;
}

.purchase-button {
  width: 150px;
}

.purchase-status {
  margin-top: 10px;
}
</style> 